package com.fc.mall.service.impl;

import com.fc.mall.dao.PmsGroupBuyDao;
import com.fc.mall.dto.PmsGroupBuy;
import com.fc.mall.dto.PmsGroupBuyParam;
import com.fc.mall.dto.PmsGroupBuyReq;
import com.fc.mall.exception.ServiceException;
import com.fc.mall.mapper.PmsProductGroupBuyMapper;
import com.fc.mall.model.PmsProductGroupBuy;
import com.fc.mall.model.PmsProductGroupBuyExample;
import com.fc.mall.service.PmsGroupBuyService;
import com.fc.mall.util.DateTimeHelper;
import com.github.pagehelper.PageHelper;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * Description:
 * User: Charles.Gao
 * Date: 2019-08-17 11:38
 */
@Service
public class PmsGroupBuyServiceImpl implements PmsGroupBuyService {
    @Autowired
    private PmsProductGroupBuyMapper pmsProductGroupBuyMapper;

    @Autowired
    private PmsGroupBuyDao pmsGroupBuyDao;

    @Autowired
    private MapperFacade mapperFacade;
    /**
     * 创建商品
     */
    @Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED)
    @Override
    public int create(PmsGroupBuyReq req)
    {
        checkTime(req);
        List<PmsProductGroupBuy> actives = queryAllActiveGroupBuysByProductId(req.getProductId());
        if (CollectionUtils.isNotEmpty(actives)) {
            throw new ServiceException("该产品已经在拼团了");
        }

        PmsGroupBuy groupBuy = new PmsGroupBuy();
        groupBuy.setActiveHour(req.getActiveHour());
        groupBuy.setGroupCount(req.getGroupCount());
        groupBuy.setGroupPrice(req.getGroupPrice());
        groupBuy.setLimitCount(req.getLimitCount());
        groupBuy.setProductId(req.getProductId());
        groupBuy.setStatus(req.getStatus());
        groupBuy.setTotalCount(req.getTotalCount());
        try{
            groupBuy.setEffectTime(DateTimeHelper.getEpochTimeFromStringFormat(req.getEffectTime(), DateTimeHelper.SQL_DATETIME));
            groupBuy.setExpiredTime(DateTimeHelper.getEpochTimeFromStringFormat(req.getExpiredTime(), DateTimeHelper.SQL_DATETIME));
        }catch (ParseException pe){
            throw new ServiceException("日期格式错误");
        }
        return pmsGroupBuyDao.insert(groupBuy);
    }

    /**
     * 根据拼团编号获取更新信息
     */
    @Override
    public PmsGroupBuy getUpdateInfo(Long id)
    {
        return pmsGroupBuyDao.selectByPrimaryKey(id);
    }

    /**
     * 更新商品
     */
    @Transactional
    @Override
    public int update(Long id, PmsGroupBuyReq req) {
        checkTime(req);

        List<PmsProductGroupBuy> actives = queryAllActiveGroupBuysByProductId(req.getProductId());
        if (CollectionUtils.isNotEmpty(actives)) {
            for (PmsProductGroupBuy gb : actives) {
                if (!gb.getId().equals(id)) {
                    throw new ServiceException("该产品已经在拼团了");
                }
            }
        }

        PmsGroupBuy groupBuy = new PmsGroupBuy();
        groupBuy.setId(id);
        groupBuy.setActiveHour(req.getActiveHour());
        groupBuy.setGroupCount(req.getGroupCount());
        groupBuy.setGroupPrice(req.getGroupPrice());
        groupBuy.setLimitCount(req.getLimitCount());
        groupBuy.setProductId(req.getProductId());
        groupBuy.setStatus(req.getStatus());
        groupBuy.setTotalCount(req.getTotalCount());
        try{
            groupBuy.setEffectTime(DateTimeHelper.getEpochTimeFromStringFormat(req.getEffectTime(), DateTimeHelper.SQL_DATETIME));
            groupBuy.setExpiredTime(DateTimeHelper.getEpochTimeFromStringFormat(req.getExpiredTime(), DateTimeHelper.SQL_DATETIME));
        }catch (ParseException pe){
            throw new ServiceException("日期格式错误");
        }

        int ret =  pmsGroupBuyDao.updateByPrimaryKey(groupBuy);
        return ret;
    }

    /**
     * 分页查询商品
     */
    @Override
    public List<PmsGroupBuy> list(PmsGroupBuyParam pmsGroupBuyParam, Integer pageSize, Integer pageNum)
    {
        PageHelper.startPage(pageNum,pageSize);
        return pmsGroupBuyDao.queryGroupBuy(pmsGroupBuyParam);
    }


    /**
     * 删除商品
     */
    @Override
    public int delete(Long id)
    {
        return pmsGroupBuyDao.deleteByPrimaryKey(id);
    }

    @Override
    public List<PmsProductGroupBuy> queryAllActiveGroupBuysByProductId(Long productId) {
        PmsProductGroupBuyExample example = new PmsProductGroupBuyExample();
        example.createCriteria().andProductIdEqualTo(productId)
                .andStatusEqualTo((byte) 1)
                .andExpiredTimeGreaterThan(DateTimeHelper.getEpochTimeInSecond(new Date()));
        List<PmsProductGroupBuy> list = pmsProductGroupBuyMapper.selectByExample(example);
        return list;
    }

    /**
     * 时间验证：结束时间应大于开始时间和当前时间
     * @param req
     */
    private void checkTime(PmsGroupBuyReq req){
        //开始时间或结束时间存在空
        if (StringUtils.isEmpty(req.getEffectTime()) ||
                StringUtils.isEmpty(req.getExpiredTime())){
            throw new ServiceException("开始时间、结束时间不可为空！");
        }
        long startTime = DateTimeHelper.getDateFromString(req.getEffectTime(),DateTimeHelper.SQL_DATETIME).getTime();
        long endTime = DateTimeHelper.getDateFromString(req.getExpiredTime(),DateTimeHelper.SQL_DATETIME).getTime();
        long now = System.currentTimeMillis();
        if (endTime <= startTime || endTime <= now) {
            throw new ServiceException("结束时间应大于开始时间和当前时间！");
        }
    }
}
